<template>
  <div class="app-container">
    <div class="bg-container">
      <div class="main-title" style="margin-top: 60px;">报告配置</div>
      <el-divider />
      <el-form ref="autoConfigurationRef" v-loading="loading" :model="form" :rules="rules" class="content"
        label-width="180">
        <el-row :gutter="15">

          <!--基础设置-->
          <el-col :span="24">
            <div class="section-title">基础设置</div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="自动报告名称" prop="autoName">
              <el-input v-model="form.autoName" placeholder="请输入自动报告名称" />
            </el-form-item>
            <el-form-item label="自动报告类型" prop="autoType">
              <el-select v-model="form.autoType" clearable filterable placeholder="请选择自动报告类型">
                <el-option label="一次性报告" value="0" />
                <el-option label="周期性报告" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="启用状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="0">正常</el-radio>
                <el-radio :value="1">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="false" label="仪表盘" prop="dataScreenId">
              <el-input v-model="form.dataScreenId" placeholder="请输入仪表盘ID" />
            </el-form-item>
          </el-col>

          <!--接收人设置-->
          <el-col :span="24">
            <div class="section-title">接收人设置</div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="接收者列表" prop="recipients">
              <el-col :span="24" class="mb8">
                <el-button icon="Plus" plain type="primary" @click="handleAddRecipient">新增
                </el-button>
              </el-col>
              <el-col :span="12">
                <el-table v-loading="loading" :data="form.recipients">
                  <el-table-column label="接收者" prop="userId">
                    <template #default="scope">
                      <el-select v-model="scope.row.userId" clearable filterable placeholder="请选择接收者"
                        @change="handleSelectChange">
                        <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="false" label="接收邮箱" prop="email">
                    <template #default="scope">
                      <el-input v-model="scope.row.email" placeholder="请输入接收邮箱" />
                    </template>
                  </el-table-column>
                  <el-table-column v-if="false" label="接收者名称" prop="name">
                    <template #default="scope">
                      <el-input v-model="scope.row.name" placeholder="请输入接收者名称" />
                    </template>
                  </el-table-column>
                  <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作">
                    <template #default="scope">
                      <el-button icon="Delete" link plain type="danger" @click="handleDeleteRecipient(scope.row)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-form-item>
          </el-col>

          <!--周期设置-->
          <el-col :span="24">
            <div class="section-title">周期设置</div>
          </el-col>
          <template v-if="form.autoType == 0">
            <el-col :span="24">
              <el-form-item label="发送报告的日期时间" prop="sendDatetime">
                <el-date-picker type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" v-model="form.sendDatetime" placeholder="请选择发送报告的日期时间"  />
              </el-form-item>
            </el-col>
          </template>
          <template v-if="form.autoType == 1">
            <el-col :span="24">
              <el-form-item label="报告频率" prop="frequency">
                <el-select v-model="form.frequency" clearable filterable placeholder="请选择报告频率">
                  <el-option label="每周" value="0" />
                  <el-option label="每月" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="form.frequency == 0" :span="12">
              <el-form-item label="发送报告的星期几" prop="sendDayOfWeek">
                <el-select v-model="form.sendDayOfWeek" clearable filterable placeholder="请选择发送报告的星期几">
                  <el-option :value="0" label="星期日" />
                  <el-option :value="1" label="星期一" />
                  <el-option :value="2" label="星期二" />
                  <el-option :value="3" label="星期三" />
                  <el-option :value="4" label="星期四" />
                  <el-option :value="5" label="星期五" />
                  <el-option :value="6" label="星期六" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="form.frequency == 1" :span="12">
              <el-form-item label="发送报告的每月几号" prop="sendDayOfMonth">
                <el-input-number v-model="form.sendDayOfMonth" :max="31" :min="1" placeholder="请输入发送报告的每月几号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发送报告的小时" prop="sendHour">
                <el-input-number v-model="form.sendHour" :max="23" :min="0" placeholder="请输入发送报告的小时" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发送报告的分钟" prop="sendMinute">
                <el-input-number v-model="form.sendMinute" :max="59" :min="0" placeholder="请输入发送报告的分钟" />
              </el-form-item>
            </el-col>
          </template>

          <!--底部按钮-->
          <el-col :span="24">
            <div class="bottom-container">
              <el-button type="primary" @click="submitForm">确认</el-button>
              <el-button @click="handleBack">返回</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script name="AutoLogConfiguration" setup>
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from 'vue'
import { configureAutoReportLog, getAutoReportLog } from "@/api/autoReportLog";
import { listTeamUserAll } from "@/api/teamUser";

const { proxy } = getCurrentInstance();

const loading = ref(false);
const userList = ref([])


const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    autoName: null,
    autoType: null,
    status: null,
    dataScreenId: null,
    frequency: null,
    sendDayOfWeek: null,
    sendDayOfMonth: null,
    sendHour: null,
    sendMinute: null,
    recipients: [],
  },
  rules: {
    autoName: [
      { required: true, message: "自动报告名称不能为空", trigger: ["blur", "change"] }
    ],
    autoType: [
      { required: true, message: "自动报告类型不能为空", trigger: ["blur", "change"] }
    ],
    status: [
      { required: true, message: "启用状态不能为空", trigger: ["blur", "change"] }
    ],
    dataScreenId: [
      { required: true, message: "仪表盘ID不能为空", trigger: ["blur", "change"] }
    ],
    frequency: [
      { required: true, message: "报告频率不能为空", trigger: ["blur", "change"] }
    ],
    sendDayOfWeek: [
      { required: true, message: "发送报告的星期几不能为空", trigger: ["blur", "change"] }
    ],
    sendDayOfMonth: [
      { required: true, message: "发送报告的每月几号不能为空", trigger: ["blur", "change"] }
    ],
    sendHour: [
      { required: true, message: "发送报告的小时不能为空", trigger: ["blur", "change"] }
    ],
    sendMinute: [
      { required: true, message: "发送报告的分钟不能为空", trigger: ["blur", "change"] }
    ],
    recipients: [
      { required: true, message: "发送报告接收人不能为空", trigger: ["blur", "change"] }
    ],
    sendDatetime: [
      { required: true, message: "发送报告的日期时间不能为空", trigger: ["blur", "change"] }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);


// 提交按钮
function submitForm() {
  proxy.$refs["autoConfigurationRef"].validate(valid => {
    if (valid) {
      if (form.value.recipients.filter(e => !e.userId).length > 0) {
        proxy.$modal.msgError("接收人不能为空");
        return
      }
      if (form.value.id != null) {
        if(form.value.autoType == 0){
          // 如果发送报告的日期时间小于等于当前时间 则阻止请求
          if(new Date(form.value.sendDatetime) <= new Date()){
            proxy.$modal.msgError("发送报告的日期时间不能小于等于当前时间");
            return
          }
        }
        configureAutoReportLog(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          handleQuery();
          handleBack();
        });
      }
    }
  });
}


function handleQuery() {
  loading.value = true;
  let id = proxy.$route.query.id;
  getAutoReportLog({ id: id }).then(response => {
    form.value = response.data;
    if (!form.value.recipients) {
      form.value.recipients = [];
    }
    form.value.status = Number(form.value.status) || 0;
    loading.value = false;
    form.value.sendDatetime &&  (form.value.sendDatetime = new Date(form.value.sendDatetime).Format("yyyy-MM-dd hh:mm:ss"))
  });
}

// 返回上一级页面
function handleBack() {
  proxy.$router.go(-1);
}

// 删除接收者
function handleDeleteRecipient(row) {
  form.value.recipients.splice(form.value.recipients.indexOf(row), 1);
}

// 新增接收者
function handleAddRecipient() {
  form.value.recipients.push({
    autoReportLogId: proxy.$route.query.id,
  });
}

// 获取接收者列表
function handleUserList() {
  let id = proxy.$route.query.id;
  listTeamUserAll({ id: id }).then(response => {
    userList.value = response.data;
  });
}

// 选择用户
function handleSelectChange(e) {
  userList.value.forEach(user => {
    if (user.id === e) {
      form.value.recipients.forEach(item => {
        if (item.userId === e) {
          item.email = user.email
          item.name = user.username
        }
      })
    }
  })
}

onMounted(() => {
  if (proxy.$route.query.id) {
    handleQuery()
    handleUserList()
  } else {
    proxy.$modal.msgError('非法跳转')
    handleBack()
  }
})
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;

  .bg-container {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    min-width: 1100px;
    box-sizing: border-box;
    padding: 80px;

    .el-select,
    .el-input {
      width: 250px !important;
    }
  }
}
</style>
